// pages/chat/chat.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 1,
    user_id: 0,
    avatar: '/static/avatar.png',
    prompt: '',
    messages: [],
    scrollY: true,
    scrollbar: false,
    scrollTop: 9999,
    btn_loading: false,
    btn_disabled: false,
    btn_disabled_background_color: '#4cd964',
    btn_text: '发送',
    safeAreaBottom: 0
  },

  onLoad: function (options) {
    const type = parseInt(options.type),
      avatar = wx.getStorageSync('avatar'),
      user_id = wx.getStorageSync('user_id');

    this.setData({
      type,
      avatar
    })

    var title = '';
    switch (type) {
      case 1:
        title = '小红书助手';
        break;
      case 2:
        title = '诗词创作助手';
        break;
      case 3:
        title = '扩写助手';
        break;
      case 4:
        title = '标题生成器助手';
        break;
      case 5:
        title = '营销文案助手';
        break;
      case 6:
        title = '朋友圈文案助手';
        break;
      case 7:
        title = '方案助手';
        break;
      case 8:
        title = '直播带货剧本助手';
        break;
      case 9:
        title = '短视频脚本助手';
        break;
      default:
        title = '智能问答';
        break;
    }
    wx.setNavigationBarTitle({
      title: title
    });

    wx.getSystemInfo({
      success: res => {
        const safeAreaBottom = this.px2rpx(res.screenHeight - res.safeArea.bottom);
        this.setData({
          safeAreaBottom
        })
      }
    })

    wx.request({
      url: getApp().globalData.ai_host + '/index/Api/getHistoryMessages',
      data: {
        user_id,
        type
      },
      success: res => {
        if (res.data.result === 1) {
          this.setData({
            messages: res.data.data
          })
          this.scrollBottom();
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  px2rpx: function (px) {
    return px * 750 / wx.getSystemInfoSync().screenWidth;
  },

  changePrompt: function (e) {
    this.setData({
      prompt: e.detail.value
    })
  },

  scrollBottom: function () {
    this.setData({
      scrollTop: this.data.scrollTop + 1
    })
  },

  sendMsg: function (e) {
    const prompt = e.detail.value ? e.detail.value : this.data.prompt,
      user_id = wx.getStorageSync('user_id'),
      type = this.data.type,
      messages = this.data.messages;

    new Promise((resolve, reject) => {
      wx.request({
        url: getApp().globalData.ai_host + '/index/Api/checkUserSendMessageAuth',
        data: {
          user_id
        },
        success: result => {
          if (result.data.result === 2) {
            wx.showToast({
              title: result.data.msg,
              icon: 'none'
            })
          } else {
            resolve()
          }
        }
      })
    }).then(() => {
      console.log('then');
      const me_message = {
        role: 'user',
        content: prompt
      }
      messages.push(me_message);

      const loading_message = {
        role: 'assistant',
        content: '内容生成中，请稍后...'
      }
      messages.push(loading_message)

      this.setData({
        prompt: '',
        btn_loading: true,
        btn_disabled: true,
        btn_disabled_background_color: '#dcd9d9',
        btn_text: '生成中...',
        messages
      })
      this.scrollBottom();

      wx.request({
        url: getApp().globalData.ai_host + '/index/Api/userTextPrompt',
        method: 'post',
        data: {
          user_id,
          prompt,
          type
        },
        success: res => {
          if (res.data.result === 1) {
            const message = res.data.data;

            this.messages = this.replaceLastSubarray(messages, message);

            this.setData({
              btn_loading: false,
              btn_disabled: false,
              btn_disabled_background_color: '#4cd964',
              btn_text: '发送',
              messages
            })
            setTimeout(() => {
              this.scrollBottom();
            }, 0)
          } else {
            this.setData({
              btn_loading: false,
              btn_disabled: false,
              btn_disabled_background_color: '#4cd964',
              btn_text: '发送'
            })

            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      })
    })
  },

  // 将二维数组中最后一项一维数据进行替换
  replaceLastSubarray: function (array, newArray) {
    if (array.length === 0) {
      // 如果二维数组为空，则直接将新数组添加到数组中
      array.push(newArray);
    } else {
      // 否则，将二维数组的最后一个元素替换为新数组
      array[array.length - 1] = newArray;
    }
    return array;
  },

  copyText: function (e) {
    const content = e.currentTarget.dataset.content;
    if (content !== '') {
      wx.setClipboardData({
        data: content,
        success: () => {
          wx.showToast({
            title: '内容已复制'
          })
        }
      })
    }
  }
})